const http = require('http')
const config = require('./config')

class Application {
    constructor(options = {}) {
        this.options = Object.assign({}, config, options)
        this.middleware = []
    }

    use(fn) {
        if (typeof fn !== 'function') {
            throw new TypeError('middleware must be a function!')
        }
        this.middleware.push(fn)
        return this
    }

    async callback(req, res) {
        if(this.middleware && this.middleware.length) {
            for(let fn of this.middleware) {
                if(typeof fn == 'function') {
                    await fn(req, res)
                }
            }
        }
        // const body = JSON.stringify(res.body)
        res.end(res.body)
    }

    listen(...args) {
        const { port, host } = this.options
        const server = http.createServer(this.callback.bind(this))
        return server.listen(...args)
    }

}

module.exports = Application